<template>
  <div class="box">
    <div v-if="token">
      <h3><span>创建书签</span>
      <el-icon style="cursor:pointer;" @click="closePopup"><Close /></el-icon>
      </h3>
      <div class="header">
        <img v-if="formData.favIconUrl" :src="formData.favIconUrl" />
        <img v-else src="../assets/TrPUZn.png" alt="">
        <div>
          <h4 :title="formData.title">{{ formData.title }}</h4>
          <p class="desc">{{ formData.description }}</p>
        </div>
      </div>
      <el-form :model="formData">
        <el-form-item label="分组">
          <el-select v-model="formData.groupId">
            <el-option
              v-for="(item, index) in groups"
              :key="index"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="标签">
          <el-select v-model="formData.tags" multiple collapse-tags collapse-tags-tooltip placeholder="请选择标签">
            <el-option v-for="(item, index) in tagOptions" :key="index" :label="item.tagName" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="URL">
          <el-input v-model="formData.url"></el-input>
        </el-form-item>
        <el-form-item label="是否星标">
          <el-checkbox v-model="formData.asterisk" :true-value="1" :false-value="0"></el-checkbox>
        </el-form-item>
      </el-form>
      <div class="foot">
        <el-button type="primary" @click="addToBookMark">添加</el-button>
      </div>
    </div>
    <div v-else style="display:flex;justify-content: center;">
      <el-button @click="goLogin" type="primary">点击登录</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from "vue";
import { ElMessage } from "element-plus";
import axios from "axios";
const token = ref("")
const user_id = ref(null)
const formData = reactive({
  userId: null,
  favIconUrl: "",
  title: "",
  description: "",
  groupId: 0,
  tags: [],
  url: "",
  asterisk: 0,
});
const groups = ref([]);
const tagOptions = ref([])

const addToBookMark = () => {
  axios({
    url: "http://localhost:23108/api/bookmarks",
    method: "post",
    data: formData,
    headers: {
      Authorization: token.value,
    },
  })
    .then((res) => {
      res.data.succeed?ElMessage.success("添加成功"):ElMessage.error("添加失败");
      setTimeout(() => {
        window.close()
      },1000)
    })
    .catch((err) => {
      ElMessage.error("添加失败");
    });
};

const getGroups = () => {
  axios({
    url: "http://localhost:23108/api/group/list/" + formData.userId,
    method: "get",
    headers: {
      Authorization: token.value,
    },
  }).then((res) => {
    const options = res.data.data?.map(item => {
      return {
        label: item.groupName,
        value: item.id
      }
    })
    groups.value = [{ label: "全部", value: 0 }].concat(options)
  })
};
const getTagOptions = () => {
  axios({
    url: "http://localhost:23108/api/tags?userId=" + formData.userId,
    method: "get",
    headers: {
      Authorization: token.value,
    },
  }).then((res) => {
    tagOptions.value = res.data.data || []
  })
}
const getWebInfo = async () => {
  const tabs = await chrome.tabs.query({ url: "*://localhost/*" });
  let targetTab = null;
  tabs.forEach((tab) => {
    if (tab.title == "收藏云书签系统" && tab.url.indexOf(":8888") != -1) {
      targetTab = tab;
    }
  });
  console.log(targetTab);
  chrome.scripting.executeScript({
    target: { tabId: targetTab?.id },
    files: ['content.js']
  });
  const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
  formData.favIconUrl = tab.favIconUrl;
  formData.title = tab.title;
  formData.url = tab.url;
  // 获取网页描述
  chrome.scripting.executeScript(
    {
      target: { tabId: tab.id },
      function: () => document.querySelector('meta[name="description"]')?.content,
    },
    (results) => {
      formData.description = results[0].result;
    }
  );
};
// 前往登录页
const goLogin = () => {
  window.open('http://localhost:8888/login')
}
const closePopup = () => {
  window.close()
}
onMounted(() => {
  getWebInfo();
  chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    if (request.action == 'SET_STORAGE') {
      if (request.data.token && request.data.user_id) {
        console.log('用户已登录');
        token.value = request.data.token
        formData.userId = Number(request.data.user_id)
        getGroups();
        getTagOptions()
      } else {
        console.error('用户未登录');
      }
    }
  })
  
});
</script>

<style scoped lang="scss">
.box {
  width: 300px;
  padding: 10px;
  h3 {
    margin: 0;
    font-size: 16px;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .header {
    display: flex;
    margin: 15px 0;
    img {
      width: 50px;
      height: 50px;
      margin-right: 15px;
    }
    h4 {
      margin: 0;
      font-size: 14px;
      max-width: 240px;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }
    .desc {
      margin: 10px 0 0 0;
      max-width: 240px;
      height: 36px;
      font-size: 12px;
      overflow: hidden;
      overflow-y: auto;
      white-space: normal;
    }
  }
  .foot {
    display: flex;
    justify-content: flex-end;
  }
}
</style>